package cn.codeforfun.vote;

import cn.codeforfun.follower.Follower;
import cn.codeforfun.follower.FollowerOption;
import cn.codeforfun.material.Material;
import cn.codeforfun.prize.Prize;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

import javax.persistence.*;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;

/**
 * 投票信息
 */
@Entity
@Table(name = "t_vote")
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class Vote {
    @Id
    @GeneratedValue
    private Long id;
    private String title;
    private String description;
    @Transient
    private Integer amount;//投票人数
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "material_id")
    private Material material;

    @ManyToMany
    @JoinTable(name = "vote_price",
            joinColumns = @JoinColumn(name = "vote_id"),
            inverseJoinColumns = @JoinColumn(name = "prize_id"))
    private Set<Prize> prizes = new LinkedHashSet<>();
    @OneToMany(cascade = CascadeType.ALL)
    @OrderBy("id asc")
    private Set<Question> questions = new LinkedHashSet<>();


    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }


    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public Set<Prize> getPrizes() {
        return prizes;
    }

    public void setPrizes(Set<Prize> prizes) {
        this.prizes = prizes;
    }

    public Set<Question> getQuestions() {
        return questions;
    }

    public void setQuestions(Set<Question> questions) {
        this.questions = questions;
    }

    public Integer getAmount() {
        Set<Follower> followers = new HashSet<>();
        for (Question question : this.getQuestions()) {
            for (Option option : question.getOptions()) {
                for (FollowerOption followerOption : option.getFollowerOptions()) {
                    followers.add(followerOption.getFollower());
                }
            }
        }
        return followers.size();
    }

    public void setAmount(Integer amount) {
        this.amount = amount;
    }

    public Material getMaterial() {
        return material;
    }

    public void setMaterial(Material material) {
        this.material = material;
    }
}
